class Posts < Controller
    helper :forum_functions
    map '/post'

    def show(post_id)
        post = get_post(post_id)

        @post_id = post.id
        @post_user = post.user.login
        @post_content = tag2html(post.content)
        @can_modify = staff_or_owner?(post)
    end

    def new
        require_login

        if request.get?
            has_citation = request[:citee_id]

            citee = get_post(request[:citee_id]) if has_citation
            topic = has_citation ? citee.topic : get_topic(request[:topic_id])

            @topic_id = topic.id
            @citee_content = has_citation ? cite(citee) : nil
            @forum_path = forum_path(topic.forum, topic)
        else
            redirect Forums.r(:list)
        end
    end

    def create
        require_login

        if request.post?
            topic = get_topic(request[:topic_id])
            post = Post.create(
                :user => user,
                :content => request[:content].esc,
                :topic => topic
            )

            redirect Topics.r(:index, topic.id)
        end
    end

    def delete(post_id)
        require_login

        post = get_post(post_id)

        if staff_or_owner?(post)
            post.destroy
        else
            flash[:error] = "Vous n'avez pas le droit de détruire ce message"
        end

        redirect Topic.r(:index, topic.id)
    end

    def edit(post_id)
        require_login

        if request.get?
            post = get_post(post_id)

            unless staff_or_owner?(post)
                flash[:error] = "Vous n'avez pas le droit de détruire ce message"
                redirect Topics.r(:index, post.topic.id)
            end

            @post_id = post.id
            @post_content = post.content

            @forum_path = forum_path(post.topic.forum, post.topic)
        end
    end

    def save(post_id)
        if request.post?
            post = get_post(post_id)

            if staff_or_owner?(post)
                post.update(
                    :content => request[:content].esc
                )
                post.save
            else
                flash[:error] = "Vous n'avez pas le droit d'éditer ce message"
            end

            redirect Topics.r(:index, post.topic.id)
        end
    end

    private

    def staff_or_owner?(post)
        (post.user.id == user.id) || (user.status == "admin")
    end

end
